import 'package:flutter/material.dart';

class DragPage extends StatefulWidget {
  @override
  _DragPageState createState() => _DragPageState();
}

class _DragPageState extends State<DragPage>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;

  @override
  void initState() {
    _controller = AnimationController(vsync: this);
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  var datas = List<String>.generate(30, (i) {
    return i.toString();
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('拖拽'),
      ),
      body: Container(
        child: Wrap(
          children: datas.map((i) {
            return _buildItem(datas.indexOf(i));
          }).toList(),
        ),
      ),
    );
  }

  Widget _buildItem(int i) {
    var item = Material(
      color: Colors.transparent,
      child: Chip(
        label: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(
            datas[i],
          ),
        ),
      ),
    );
    var draggable = Draggable<String>(
      feedback: item,
      child: item,
      childWhenDragging: Opacity(
        opacity: 0.5,
        child: item,
      ),
      data: datas[i],
    );
    return _buildTarget(draggable, i);
  }

  Widget _buildTarget(Widget draggable, int index) {
    var builder = (ctx, List<String> list, List list2) {
      return draggable;
    };
    return DragTarget<String>(
      builder: builder,
      onAccept: (String value) {
        var src = datas.indexOf(value);
        datas[src] = datas[index];
        datas[index] = value;
        setState(() {
          print(datas);
        });
      },
      onWillAccept: (value) {
        print(value);
        return true;
      },
    );
  }
}
